package com.UnionPayCenter.service.serviceImpl;

import com.UnionPayCenter.constant.ConstantInterface;
import com.UnionPayCenter.constant.CouponConstants;
import com.UnionPayCenter.coupon.service.CouponQueryService;
import com.UnionPayCenter.domain.UserQuery;
import com.UnionPayCenter.entity.*;
import com.UnionPayCenter.entity.vo.CardInfoVo;
import com.UnionPayCenter.entity.vo.ExpiringUserCouponVo;
import com.UnionPayCenter.entity.vo.UserCouponVo;
import com.UnionPayCenter.entity.vo.UserVo;
import com.UnionPayCenter.enums.ErrorCodeEnum;
import com.UnionPayCenter.exception.ApiException;
import com.UnionPayCenter.mapper.*;
import com.UnionPayCenter.request.PutToUserConditionRequest;
import com.UnionPayCenter.service.ICouponService;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.IWechatService;
import com.UnionPayCenter.util.CSVUtil;
import com.UnionPayCenter.util.DateFormatUtil;
import com.UnionPayCenter.util.IdGen;
import com.UnionPayCenter.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CardInfoMapper cardInfoMapper;

    @Autowired
    private ConfMapper confMapper;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private IUserService userService;

    @Autowired
    private CouponQueryService couponQueryService;


    @Override
    public PageInfo<CouponEntity> findList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            String disName = jsonParam.getString("name");
            String disType = jsonParam.getString("disType");
            String validTag = jsonParam.getString("validTag");
            List<CouponEntity> list = couponMapper.selectList(shopId, disName, disType,validTag);
            PageInfo<CouponEntity> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean add(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String disName = jsonParam.getString("name");
            Integer num = jsonParam.getInteger("num");
            Integer validDays = jsonParam.getInteger("validDays");
            Integer minAmount = jsonParam.getInteger("minAmount");
            Integer maxAmount = jsonParam.getInteger("maxAmount");
            String disType = jsonParam.getString("disType");
            Integer stock = jsonParam.getInteger("stock");
            String limitStock = jsonParam.getString("limitStock");
            String limitTime = jsonParam.getString("limitTime");

            if (limitStock.equals(CouponConstants.LIMIT_STOCK_YES) && stock == null) {
                throw new ApiException(ErrorCodeEnum.CP6004);
            }

            List<CouponEntity> exists = couponMapper.selectList(shopId, disName, null,null);
            if (exists.size() > 0) {
                throw new ApiException(ErrorCodeEnum.CP6005);
            }

            CouponEntity couponEntity = new CouponEntity();
            couponEntity.setBId(shopId);
            couponEntity.setDisName(disName);
            couponEntity.setValidDays(validDays);
            couponEntity.setNum(num);
            couponEntity.setMinAmount(minAmount);
            couponEntity.setMaxAmount(maxAmount);
            couponEntity.setStock(stock);
            couponEntity.setLeftStock(stock);
            couponEntity.setLimitStock(limitStock);
            couponEntity.setDisType(disType);
            couponEntity.setLimitTime(limitTime);
            //永久有效优惠券设置有效天数为10000
            if (limitTime.equals(CouponConstants.LIMIT_TIME_NO)) {
                couponEntity.setValidDays(CouponConstants.VALID_FOREVER_DAYS);
            }

            //默认限制使用次数：一次性使用
            couponEntity.setLimitUsed(CouponConstants.LIMIT_USE_YES);
            //默认可以重复持有
            couponEntity.setReUsed(CouponConstants.RE_USED_YES);
            //默认赠送类型：其他
            couponEntity.setType(CouponConstants.GIFT_TYPE_OTHER);
            //默认优先级
            couponEntity.setPrLev(CouponConstants.PRIORITY_DEFAULT);
            //默认优惠区间限时
            couponEntity.setTimeStart(CouponConstants.DISCOUNT_TIME_START);
            couponEntity.setTimeEnd(CouponConstants.DISCOUNT_TIME_END);

            couponMapper.insertSelective(couponEntity);
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public CouponEntity findCouponInfo(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer disTypeId = jsonParam.getInteger("disTypeId");

            CouponEntity couponEntity = couponMapper.selectByPrimaryKey(disTypeId);
            if (couponEntity == null) {
                throw new ApiException(ErrorCodeEnum.CP6002.code(), String.format(ErrorCodeEnum.CP6002.msg(), "disTypeId"));
            }

            return couponEntity;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public boolean update(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            Integer disTypeId = jsonParam.getInteger("disTypeId");
            String limitStock = jsonParam.getString("limitStock");
            Integer stock = jsonParam.getInteger("stock");

            CouponEntity exists = couponMapper.selectByPrimaryKey(disTypeId);
            if (exists == null) {
                throw new ApiException(ErrorCodeEnum.CP6002.code(), String.format(ErrorCodeEnum.CP6002.msg(), "disTypeId"));
            }

            if (CouponConstants.LIMIT_STOCK_NO.equals(exists.getLimitStock()) && limitStock.equals(CouponConstants.LIMIT_STOCK_YES)) {
                throw new ApiException(ErrorCodeEnum.CP6003);
            }

            //计算剩余库存,剩余库存  = 更新后的总库存  - 已使用的库存
            Integer usedStock = exists.getStock() - exists.getLeftStock();
            Integer leftStock = stock - usedStock;

            CouponEntity couponEntity = new CouponEntity();
            couponEntity.setDisTypeId(disTypeId);
            couponEntity.setLimitStock(limitStock);
            couponEntity.setStock(stock);
            couponEntity.setLeftStock(leftStock);

            couponMapper.updateByPrimaryKeySelective(couponEntity);
            return true;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public void updateUserId(Long userId, String couponsId) {
        userCouponMapper.updateUserId(userId, couponsId);
    }

    @Override
    public PageInfo<UserCouponVo> findUserCouponList(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            this.updateExpiredCoupon(shopId);

            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            String mobile = jsonParam.getString("mobile");
            String status = jsonParam.getString("status");
            String disType = jsonParam.getString("disType");
            Integer deliverTime = jsonParam.getInteger("deliverTime");

            //status多选处理
            String[] stArray = null;
            if (StringUtils.isNotBlank(status)) {
                stArray = status.split(Pattern.quote(","));
            }

            //投放时间筛选，获取开始时间与结束时间
            Map<String, Date> dateMap = this.getDeliverTime(deliverTime);
            Date startTime = dateMap.get("startTime");
            Date endTime = dateMap.get("endTime");

            List<UserCouponVo> list = couponMapper.selectUserCouponList(shopId, mobile, stArray, null, "Y", disType, startTime, endTime);
            PageInfo<UserCouponVo> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    /**
     * 获取投放时间,获取开始时间与结束时间
     *
     * @param deliverTime
     * @return
     */
    private Map<String, Date> getDeliverTime(Integer deliverTime) {
        Map<String, Date> dateMap = new HashMap<>();
        if (Objects.isNull(deliverTime)) {
            return dateMap;
        }

        Date startDate = null;
        Date today = DateFormatUtil.getTodayStartTime(new Date());
        if (deliverTime.equals(CouponConstants.ONE_DAY)) { //今日投放
            startDate = today;
        } else if (deliverTime.equals(CouponConstants.ONE_WEEK)) { //最近一周(包含单天数据)
            startDate = DateFormatUtil.dayCalculate(today, -6);
        } else if (deliverTime.equals(CouponConstants.ONE_MONTH)) { //最近一月(包含单天数据)
            startDate = DateFormatUtil.dayCalculate(today, -29);
        } else if (deliverTime.equals(CouponConstants.THREE_MONTH)) { //最近三月(包含单天数据)
            startDate = DateFormatUtil.dayCalculate(today, -89);
        }
        Date endDate = DateFormatUtil.dayCalculate(today, 1);

        dateMap.put("startTime", startDate);
        dateMap.put("endTime", endDate);
        return dateMap;
    }

    /**
     * 更新已过期优惠券状态
     *
     * @param shopId
     */
    private void updateExpiredCoupon(Integer shopId) {
        Date now = new Date();
        List<UserCouponEntity> expiredList = couponMapper.getExpiredCouponList(shopId, now, CouponConstants.COUPON_STATUS_AVL);
        if (expiredList.size() > 0) {
            for (UserCouponEntity userCoupon : expiredList) {
                couponMapper.updateExpiredCoupon(userCoupon.getId(), CouponConstants.COUPON_STATUS_EXPIRED);
            }
        }

    }

    @Override
    public String putToConditionUser(PutToUserConditionRequest putToUserConditionRequest, Integer shopId, Integer managerId) {
        UserQuery userQuery = new UserQuery();
        userQuery.setEndAmount(putToUserConditionRequest.getEndAmount());
        userQuery.setEndTime(putToUserConditionRequest.getEndTime());
        userQuery.setMobile(putToUserConditionRequest.getMobile());
        userQuery.setStartAmount(putToUserConditionRequest.getStartAmount());
        userQuery.setUserLevel(putToUserConditionRequest.getUserLevel());
        userQuery.setStartTime(putToUserConditionRequest.getStartTime());
        userQuery.setStartTotalAmount(putToUserConditionRequest.getStartTotalAmount());
        userQuery.setEndTotalAmount(putToUserConditionRequest.getEndTotalAmount());

        List<UserVo> list =   userService.findList(userQuery,shopId);
        if(CollectionUtils.isEmpty(list)){
            throw new ApiException(ErrorCodeEnum.CP6007.code(), String.format(ErrorCodeEnum.CP6007.msg(), "managerId"));
        }
        String mobiles = list.stream().map(UserVo::getMobile).distinct().collect(Collectors.joining(","));
        putToUserConditionRequest.setMobiles(mobiles);
        String str = JSONObject.toJSONString(putToUserConditionRequest);
        return putToUser(JSONObject.parseObject(str));
    }

    @Override
    public String putToUser(JSONObject jsonParam) {
        String result = "目标发放[%s]张优惠券，实际发出[%s]张";

        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String mobiles = jsonParam.getString("mobiles");
            Integer disTypeId = jsonParam.getInteger("disTypeId");
            Integer count = jsonParam.getInteger("count");
            Integer effectiveNextDay = jsonParam.getInteger("effectiveNextDay");
            if(!couponQueryService.checkCouponValidTag(disTypeId)){
                return "优惠券已停用。投放不成功";
            }

            //多用户投放
            String[] mobileArray = null;
            if (StringUtils.isNotBlank(mobiles)) {
                mobileArray = mobiles.split(Pattern.quote(","));
            }

            Integer mobileCount = mobileArray.length;
            //目标投放数
            Integer expectDeliver = mobileCount * count;
            //实际投放数
            Integer actualDeliver = 0;
            for (int i = 0; i < mobileCount; i++) {
                String mobile = mobileArray[i];
                try {
                    this.insertUserCoupon(shopId, mobile, disTypeId, count, effectiveNextDay);
                    actualDeliver = actualDeliver + count;
                } catch (ApiException e) {
                    log.error("给用户" + mobile + "投放优惠券失败: [{}]", e.getMessage());
                    //若投放第一个用户时就失败，则抛出异常;否则不抛出
                    if (i == 0) {
                        throw e;
                    }
                } catch (Exception e) {
                    log.error("给用户" + mobile + "投放优惠券失败: [{}]", e.getMessage());
                    throw e;
                }
            }

            return String.format(result, expectDeliver, actualDeliver);
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    /**
     * @param shopId
     * @param userId
     * @param disTypeId
     * @param count
     * @param effectiveNextDay (1-次日生效;0-即刻生效)
     * @Description: 插入用户优惠券信息
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void insertUserCouponByUserId(Integer shopId, Integer userId, Integer disTypeId, Integer count, Integer effectiveNextDay) {
        UserCouponEntity userCouponEntity = new UserCouponEntity();
        CouponEntity coupon = couponMapper.selectByPrimaryKey(disTypeId);
        if (coupon != null) {
            if(!couponQueryService.checkCouponValidTag(coupon.getDisTypeId())){
                log.warn("优惠券已停用："+coupon);
                return ;
            }
            //如果是限制库存数量的优惠券，判断投放数量是否大于剩余库存
            String limitStock = coupon.getLimitStock();
            Integer leftStock = coupon.getLeftStock();
            if (limitStock.equals(CouponConstants.LIMIT_STOCK_YES) && count > leftStock) {
                throw new ApiException(ErrorCodeEnum.CP6001);
            }

            //领取优惠券时间
            Date today = new Date();
            //优惠券生效时间
            Date effectiveDay = today;
            if (effectiveNextDay.equals(CouponConstants.EFFECTIVE_NEXT_DAY_YES)) {
                effectiveDay = DateFormatUtil.getTodayStartTime(DateFormatUtil.dayCalculate(today, 1));
            }
            //优惠券到期时间
            Date expireDay = DateFormatUtil.dayCalculate(effectiveDay, coupon.getValidDays());

            String endTime = DateFormatUtil.dateToString(expireDay);
            for (int i = 0; i < count; i++) {
                userCouponEntity.setUserId(userId);
                userCouponEntity.setDisId(IdGen.newStringId());
                userCouponEntity.setDisTypeId(disTypeId);
                userCouponEntity.setLimitUsed(coupon.getLimitUsed());
                userCouponEntity.setDisSt(CouponConstants.COUPON_STATUS_AVL);
                userCouponEntity.setUsedTime("");//初始化为空

                userCouponEntity.setGetTime(DateFormatUtil.dateToString(today));
                userCouponEntity.setEndTime(endTime);
                userCouponEntity.setEffectiveTime(DateFormatUtil.dateToString(effectiveDay));

                couponMapper.insertUserCoupon(userCouponEntity);
            }
            wechatService.pushCouponsNotify(shopId, userId, coupon, endTime, count);

            //如果是限制库存数量的优惠券，计算投放后的剩余库存并更新到优惠券类型表
            if (limitStock.equals(CouponConstants.LIMIT_STOCK_YES)) {
                Integer left = leftStock - count;
                CouponEntity newEntity = new CouponEntity();
                newEntity.setDisTypeId(disTypeId);
                newEntity.setLeftStock(left);
                couponMapper.updateByPrimaryKeySelective(newEntity);
            }
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "disTypeId"));
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insertUserCoupon(Integer shopId, String mobile, Integer disTypeId, Integer count, Integer effectiveNextDay) {
        UserVo user = userMapper.selectByMobile(shopId, mobile);
        if (user == null) {
            throw new ApiException(ErrorCodeEnum.FL500.code(), String.format(ErrorCodeEnum.FL500.msg().concat("[%s]"), mobile.concat(
                    ":该手机号用户不存在")));
        }
        insertUserCouponByUserId(shopId, user.getUserId(), disTypeId, count, effectiveNextDay);
    }

    @Override
    public PageInfo<UserCouponVo> getUserCouponList(JSONObject jsonParam) {
        Integer shopId = jsonParam.getInteger("shopId");
        Integer userId = jsonParam.getInteger("userId");
        String mobile = jsonParam.getString("mobile");
        String status = jsonParam.getString("status");
        Integer payAmount = jsonParam.getInteger("payAmount");

        //status多选处理
        String[] stArray = null;
        if (StringUtils.isNotBlank(status)) {
            stArray = status.split(Pattern.quote(","));
        }

        this.updateExpiredCoupon(shopId);

        // 页数
        Integer page = jsonParam.getInteger("page");
        if (page == null) {
            page = 1;
        }
        // 每页条数
        Integer pageSize = jsonParam.getInteger("pageSize");
        if (pageSize == null) {
            pageSize = 20;
        }
        PageHelper.startPage(page, pageSize);

        List<UserCouponVo> pageList = couponMapper.selectUserCouponList(shopId, mobile, stArray, userId, null, null, null, null);
        PageInfo<UserCouponVo> originPageInfo = new PageInfo<>(pageList);

        List<UserCouponVo> fullList = couponMapper.selectUserCouponList(shopId, mobile, stArray, userId, null, null, null, null);
        PageInfo<UserCouponVo> resultList = new PageInfo<>();
        BeanUtils.copyProperties(originPageInfo, resultList);
        if (originPageInfo.getSize() != 0) {
            resultList.setList(getUnusableReason(fullList, payAmount).subList(originPageInfo.getStartRow() - 1,
                    originPageInfo.getEndRow()));
        }
        return resultList;
    }

    /**
     * 设置不可用原因
     * 并将不可用优惠券放在可用优惠券之后
     *
     * @param list
     * @param payAmount
     * @return
     */
    private List<UserCouponVo> getUnusableReason(List<UserCouponVo> list, Integer payAmount) {
        List<UserCouponVo> usableList = new ArrayList<>();
        List<UserCouponVo> unusableList = new ArrayList<>();
        Date now = new Date();
        if (CollectionUtils.isNotEmpty(list)) {
            for (UserCouponVo coupon : list) {
                if (Objects.isNull(coupon)) {
                    continue;
                }
                Date effectiveTime = DateFormatUtil.stringToDate(coupon.getEffectiveTime());
                if ((Objects.isNull(payAmount) || null == coupon.getMinAmount() || coupon.getMinAmount() <= payAmount)
                        && now.compareTo(effectiveTime) >= 0) {
                    coupon.setUnUsableMsg("");
                    usableList.add(coupon);
                } else {
                    if (Objects.nonNull(payAmount) && null != coupon.getMinAmount() && coupon.getMinAmount() > payAmount) {
                        coupon.setUnUsableMsg(CouponConstants.AMOUNT_NOT_ENOUGH);
                    }
                    if (now.compareTo(effectiveTime) < 0) {
                        coupon.setUnUsableMsg(CouponConstants.NOT_EFFECTIVE_YET);
                    }
                    unusableList.add(coupon);
                }
            }
        }

        //不可用优惠券排在可用优惠券之后
        usableList.addAll(unusableList);
        return usableList;
    }

    @Override
    public CardInfoVo getCardInfoByUserId(Integer userId) {
        if (userId == null) {
            throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "userId"));
        }
        CardInfoVo cardInfo = cardInfoMapper.selectCardInfoByUserId(userId);
        return cardInfo;
    }

    @Override
    public CardInfoVo getCardInfoByCardId(String cardId) {
        if (cardId == null) {
            throw new ApiException(ErrorCodeEnum.SW11.code(), String.format(ErrorCodeEnum.SW11.msg(), "cardId"));
        }
        CardInfoVo cardInfo = cardInfoMapper.selectCardInfoByCardId(cardId);
        return cardInfo;
    }

    @Override
    public boolean consumptionCoupon(Integer userId, String disId) {
        //使用优惠券时间
        String usedTime = DateFormatUtil.dateToString(new Date());

        UserCouponEntity userCoupon = new UserCouponEntity();
        userCoupon.setUserId(userId);
        userCoupon.setDisId(disId);
        userCoupon.setUsedTime(usedTime);
        userCoupon.setDisSt(CouponConstants.COUPON_STATUS_USED);

        couponMapper.consumptionCoupon(userCoupon);
        return true;
    }

    @Override
    public UserCouponVo getUserCouponByDisId(Integer userId, String disId) {
        UserCouponVo userCoupon = couponMapper.getUserCouponByDisId(userId, disId);
        return userCoupon;
    }

    @Override
    public int getUserCouponCount(Integer userId, Integer shopId, String status) {
        int count = couponMapper.getUserCouponCount(userId, shopId, status);
        return count;
    }

    @Override
    public PageInfo<CouponDeliverRecords> findCouponDeliverRecords(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            String mobile = jsonParam.getString("mobile");
            String disType = jsonParam.getString("disType");
            String startTime = jsonParam.getString("startTime");
            String endTime = jsonParam.getString("endTime");
            List<CouponDeliverRecords> list = couponMapper.selectCouponDeliverRecords(shopId, mobile, disType, startTime, endTime);
            PageInfo<CouponDeliverRecords> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public String exportDeliverRecords(JSONObject jsonParam) throws IOException {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String mobile = jsonParam.getString("mobile");
            String disType = jsonParam.getString("disType");
            String startTime = jsonParam.getString("startTime");
            String endTime = jsonParam.getString("endTime");
            List<CouponDeliverRecords> list = couponMapper.selectCouponDeliverRecords(shopId, mobile, disType, startTime, endTime);

            String[] propertyName = new String[5];
            propertyName[0] = "手机号";
            propertyName[1] = "优惠券名称";
            propertyName[2] = "有效期";
            propertyName[3] = "投放张数";
            propertyName[4] = "投放时间";

            List<List<String>> exportData = new ArrayList<List<String>>();
            List<String> row;
            if (list != null) {
                for (CouponDeliverRecords records : list) {
                    row = new ArrayList<>();
                    row.add(records.getMobile());
                    row.add(records.getDisName());
                    if (CouponConstants.LIMIT_TIME_YES.equals(records.getLimitTime())) {
                        row.add(records.getValidDays().toString());
                    } else {
                        row.add("永久有效");
                    }
                    row.add(records.getCount().toString());
                    row.add(records.getGetTime());
                    exportData.add(row);
                }
            }

            String name = "/CouponDeliverRecords-" + DateFormatUtil.getYYYY_MM_DD() + ".xls";
            CSVUtil.poiExcel(name, "优惠券投放记录", propertyName, exportData);

            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.DOMAIN_URL);
            return confEntity.getConfValue() + name;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public PageInfo<CouponUseRecords> findCouponUseRecords(JSONObject jsonParam) {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            // 页数
            Integer page = jsonParam.getInteger("page");
            if (page == null) {
                page = 1;
            }
            // 每页条数
            Integer pageSize = jsonParam.getInteger("pageSize");
            if (pageSize == null) {
                pageSize = 20;
            }
            PageHelper.startPage(page, pageSize);

            String mobile = jsonParam.getString("mobile");
            String disType = jsonParam.getString("disType");
            String startTime = jsonParam.getString("startTime");
            String endTime = jsonParam.getString("endTime");
            List<CouponUseRecords> list = couponMapper.selectCouponUseRecords(shopId, mobile, disType, startTime, endTime);
            PageInfo<CouponUseRecords> pageList = new PageInfo<>(list);
            return pageList;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    @Override
    public String exportUseRecords(JSONObject jsonParam) throws IOException {
        Integer managerId = jsonParam.getInteger("managerId");
        Integer shopId = jsonParam.getInteger("shopId");
        ManagerEntity managerEntity = managerMapper.selectByShopId(managerId, shopId);
        if (managerEntity != null) {
            String mobile = jsonParam.getString("mobile");
            String disType = jsonParam.getString("disType");
            String startTime = jsonParam.getString("startTime");
            String endTime = jsonParam.getString("endTime");
            List<CouponUseRecords> list = couponMapper.selectCouponUseRecords(shopId, mobile, disType, startTime, endTime);

            String[] propertyName = new String[4];
            propertyName[0] = "手机号";
            propertyName[1] = "优惠券名称";
            propertyName[2] = "优惠金额";
            propertyName[3] = "使用时间";

            List<List<String>> exportData = new ArrayList<List<String>>();
            List<String> row;
            if (list != null) {
                for (CouponUseRecords records : list) {
                    //优惠金额单位转换为元
                    BigDecimal amount = new BigDecimal(records.getAmount());
                    amount = amount.divide(new BigDecimal(100));

                    row = new ArrayList<>();
                    row.add(records.getMobile());
                    row.add(records.getDisName());
                    row.add(amount.toString());
                    row.add(records.getUsedTime());
                    exportData.add(row);
                }
            }

            String name = "/CouponUseRecords-" + DateFormatUtil.getYYYY_MM_DD() + ".xls";
            CSVUtil.poiExcel(name, "优惠券使用记录", propertyName, exportData);

            ConfEntity confEntity = confMapper.selectByKey(ConstantInterface.DOMAIN_URL);
            return confEntity.getConfValue() + name;
        } else {
            throw new ApiException(ErrorCodeEnum.SW10.code(), String.format(ErrorCodeEnum.SW10.msg(), "managerId"));
        }
    }

    /**
     * 根据优惠券ID获取优惠券信息
     *
     * @param disTypeId
     * @return
     */
    @Override
    public CouponEntity getCouponMapperByTypeId(Long disTypeId) {
        return couponMapper.selectByPrimaryKey(disTypeId);
    }

    @Override
    public List<ExpiringUserCouponVo> getExpiringUserCoupon(String expireDate) {
        if (StringUtils.isBlank(expireDate)) {
            return new ArrayList<>();
        }
        return couponMapper.selectExpiringUserCoupon(expireDate);
    }

}
